#!/usr/bin/env python


__author__= 'yingnn'

'''methylation fitting using random forest'''


import sys


if len(sys.argv) < 3:
	print sys.argv[0], "fname n_trees n_jobs\n200 trees recommended as a start.\n"
	exit()

fname=sys.argv[1]
n_trees=int(sys.argv[2])
# n_trees=sys.argv[2]
jobs=int(sys.argv[3])
n_col_sampling=int(sys.argv[4])

# these modules should have been installed. Or u maybe try setting environment variable "export PYTHONPATH=$PYTHONPATH:/mnt/ilustre/app/medical/tools/py_module"
import pandas as pd
import numpy as np
import random
from sklearn.ensemble import RandomForestClassifier as rfc

dat= pd.read_csv(fname)

# dat= dat.transpose()

dat1= dat.dropna(axis=1, how='any') # drop columns if there is a not-available value in them. 

# thresh= .6

# dat2= pd.concat([dat1.iloc[:, 0], dat1.iloc[:, 1:] > thresh], axis=1)

n_sample= dat1.shape[0]
n_sampling=n_sample/3

n_col=dat1.shape[1]

idx_sample_bool= np.repeat(True, n_sample)

idx_sample= np.arange(n_sample)
idx_col= np.arange(1, n_col)



idx_valid= random.sample(idx_sample, n_sampling)

idx_col= random.sample(idx_col, n_col_sampling)

sample_valid= dat1.loc[idx_valid]

idx_sample_bool[idx_valid]=False
sample_train= dat1.loc[idx_sample[idx_sample_bool]]


	
rfc1= rfc(n_estimators=n_trees, oob_score=True, n_jobs=jobs, verbose=10)

# rfc1.fit(dat1.iloc[1:, 1:], dat1.iloc[1:, 0]) # [x,y], x is like [n_samples, n_features], y is like [n_samples, ]

# rfc1.fit(sample_train.iloc[:, 1:], sample_train.iloc[:, 0])
rfc1.fit(sample_train.iloc[:, idx_col], sample_train.iloc[:, 0])

#pred= rfc1.predict(x_new)
# proba= rfc1.predict_proba(x_new)
# sc= rfc1.score(sample_valid.iloc[:, 1:], sample_valid.iloc[:, 0])
sc= rfc1.score(sample_valid.iloc[:, idx_col], sample_valid.iloc[:, 0])
# rfc1.classes_ # list of classes
# rfc1.n_classes_ # number of classes
# rfc1.n_features_
# rfc1.feature_importances_



f= open('score_tf.txt', 'a')
f.write("\t".join([str(rfc1.oob_score_), str(sc), fname])+ "\n")
f.close()



